package com.wobito.controller.operate;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wobito.common.constants.BaseResponse;
import com.wobito.common.constants.BusinessException;
import com.wobito.common.constants.ErrorCode;
import com.wobito.common.constants.SysConstants;
import com.wobito.common.utils.DateUtils;
import com.wobito.common.utils.LockUtils;
import com.wobito.common.utils.ResultUtils;
import com.wobito.pojo.bean.Cabinet;
import com.wobito.pojo.bean.ConfigData;
import com.wobito.pojo.bean.ConfigType;
import com.wobito.pojo.bean.DeviceLog;
import com.wobito.pojo.dto.book.BookByQueryNameDTO;
import com.wobito.pojo.dto.config.ConfigPictureDTO;
import com.wobito.pojo.result.BookByQueryResult;
import com.wobito.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Wangbaba
 * @Date 2024/9/2 10:05
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/operate/getInfo")
@Api(tags = "获取各种数据接口")
public class ObtainInfoController {

    @Autowired
    private CabinetLatService cabinetLatService;
    @Autowired
    private ICabinetService cabinetService;
    @Autowired
    private BookService bookService;
    @Autowired
    private IDeviceLogService deviceLogService;
    @Autowired
    private IConfigTypeService configTypeService;
    @Autowired
    private IConfigDataService configDataService;

    @GetMapping("/getCabinetId/{sequenceCode}")
    @ApiOperation(value = "根据柜子序列号获取柜子ID")
    public BaseResponse getCabinetId(@PathVariable("sequenceCode") String sequenceCode) {
        Cabinet cabinet=cabinetService.getOne(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getSequenceCode, sequenceCode));
        if (ObjectUtil.isNull(cabinet)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "未查询到该柜子");
        }
        deviceLogService.insertDeviceLog(new DeviceLog(null, DateUtils.getNowDate(), null, "根据柜子序列号获取柜子ID"));
        return ResultUtils.success(cabinet.getId());
    }

    @GetMapping("/getAllLats/{cabinetId}")
    @ApiOperation(value = "根据柜子ID获取所有的柜格(数据刷新)")
    public BaseResponse getAllCabinetLats(@PathVariable("cabinetId") Long cabinetId) {
        deviceLogService.insertDeviceLog(new DeviceLog(null, DateUtils.getNowDate(), null, "根据柜子ID获取所有的柜格(数据刷新)"));
        return ResultUtils.success(cabinetLatService.selectCabinetLats(cabinetId));
    }

    @GetMapping("/getAllCabinetLats/{cabinetId}")
    @ApiOperation(value = "根据柜子ID获取所有的柜格(界面显示)")
    public BaseResponse getAllCabinetLats(@PathVariable("cabinetId") Long cabinetId, @RequestParam("personId") Long personId) {
        deviceLogService.insertDeviceLog(new DeviceLog(null, DateUtils.getNowDate(), personId, "根据柜子ID获取所有的柜格(界面显示)"));
        return ResultUtils.success(cabinetLatService.selectCabinetLats(cabinetId));
    }

    @GetMapping("/getLatFile/{latId}")
    @ApiOperation("根据柜格ID获取柜格下的书籍(在库的)")
    public BaseResponse getCabinetLatFile(@PathVariable("latId") Long latId, @RequestParam("personId") Long personId) {
        deviceLogService.insertDeviceLog(new DeviceLog(latId, DateUtils.getNowDate(), personId, "根据柜子ID获取所有的柜格(界面显示)"));
        return ResultUtils.success(bookService.selectFilesByLatId(latId));
    }

    @GetMapping("/getFileByName")
    @ApiOperation("根据条件搜索书籍信息(在库的)")
    public BaseResponse getFileByName(@RequestParam(value = "cabinetId") Long cabinetId,
                                      @RequestParam(value = "personId") Long personId,
                                      @RequestParam(value = "name") String queryNmae) {
        List<BookByQueryNameDTO> books = bookService.selectFileByQueryName(queryNmae);
        if (CollectionUtils.isEmpty(books)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "未查询到该书籍");
        }
        //增加搜索次数
        List<Long> bookId = books.stream().map(BookByQueryNameDTO::getId).collect(Collectors.toList());
        synchronized (LockUtils.getLock(LockUtils.QUERY_NUM_LOCK + cabinetId)) {
            bookService.updateQueryNumById(bookId);
        }
        boolean isThis = books.stream().anyMatch(b -> b.getCabinetId().equals(cabinetId));
        BookByQueryResult result = new BookByQueryResult(isThis, books);
        deviceLogService.insertDeviceLog(new DeviceLog(null, DateUtils.getNowDate(), personId, "根据条件搜索书籍信息(在库的)"));
        return ResultUtils.success(result);
    }

    @GetMapping("/getConfig")
    @ApiOperation(value = "获取各种配置")
    public BaseResponse getConfigList() {
        Map<String, Object> configValueMap = new HashMap<>();
        ConfigType configOpenTime = configTypeService.getOne(new LambdaQueryWrapper<ConfigType>().eq(ConfigType::getConfigKey, "system:device:openTime"));
        ConfigType configColseTime = configTypeService.getOne(new LambdaQueryWrapper<ConfigType>().eq(ConfigType::getConfigKey, "system:device:closeTime"));
        List<ConfigData> configPictures = configDataService.list(new LambdaQueryWrapper<ConfigData>().eq(ConfigData::getConfigKey, "picture:list:config"));
        List<ConfigPictureDTO> configPictureDTOS = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(configPictures)) {
            configPictureDTOS = configPictures.stream().map(p -> {
                ConfigPictureDTO pictureDTO = new ConfigPictureDTO();
                pictureDTO.setIndex(p.getConfigLabel());
                pictureDTO.setUrl(p.getConfigValue());
                return pictureDTO;
            }).collect(Collectors.toList());
        }
        configValueMap.put("[设备自动开机时间]-system:device:openTime", configOpenTime.getConfigValue());
        configValueMap.put("[设备自动关机时间]-system:device:closeTime", configColseTime.getConfigValue());
        configValueMap.put("[图片配置数据]-picture:list:config", configPictureDTOS);
        deviceLogService.insertDeviceLog(new DeviceLog(null, DateUtils.getNowDate(), null, "获取各种配置"));
        return ResultUtils.success(configValueMap);
    }

    @GetMapping("/getCabinetShowDate/{cabinetId}")
    @ApiOperation(value = "根据柜子ID获取各种统计数据")
    public BaseResponse getCabinetShowDate(@PathVariable("cabinetId") Long cabinetId){
        Map<String,Object> dateMap = new HashMap<>();
        Long bookByCabinetNum = bookService.selectBookNumByCabinet(cabinetId,null);
        Long invBookNum = bookService.selectBookNumByCabinet(cabinetId, SysConstants.STATE_FILE_ZK);
        dateMap.put("本柜库存",bookByCabinetNum);
        dateMap.put("本柜在库",invBookNum);
        return ResultUtils.success(dateMap);
    }

    @GetMapping("/getBookByRFID/{rfid}")
    @ApiOperation(value = "根据RFID获取书籍")
    public BaseResponse getBookByRFID(@PathVariable("rfid") String rfid) {
        deviceLogService.insertDeviceLog(new DeviceLog(null, DateUtils.getNowDate(), null, "根据RFID获取书籍"));
        return ResultUtils.success(bookService.selectBookByRFID(rfid));
    }

}
